package com.mayikt.main.manage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mayikt.common.core.utils.RedisUtil;
import com.mayikt.main.api.impl.entity.SysUserLoginLog;
import com.mayikt.main.api.impl.mapper.SysUserLoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 余胜军
 * @ClassName LoginLogManage
 * @qq 644064779
 * @addres www.mayikt.com
 * 微信:yushengjun644
 */
@Component
@Slf4j
@EnableAsync
public class LoginLogManage {
    @Autowired
    private SysUserLoginLogMapper sysUserLoginLogMapper;

    /**
     * 默认的情况下 如果我们整合 @Async
     * 直接 new 单独线程处理
     * 整合线程池
     * 16核* 最佳线程数=16核*2=32
     */
//    @Async("taskExecutor")
    @Transactional
    public boolean asynLoginLog(SysUserLoginLog sysUserLoginLog) {
        //1.先根据userid 查询日志表 如果有登录记录 ----
        //2.将原来登录日志token  从redis删除
        QueryWrapper<SysUserLoginLog> loginLogQueryWrapper = new QueryWrapper<>();
        loginLogQueryWrapper.eq("user_id", sysUserLoginLog.getUserId());
        loginLogQueryWrapper.eq("is_delete", 0);
        SysUserLoginLog dbUserLoginLog = sysUserLoginLogMapper.selectOne(loginLogQueryWrapper);
        String loginToken = null;  // 上一次登录
        if (dbUserLoginLog != null) {
            // 需要获取到上一次登录的token
            loginToken = dbUserLoginLog.getLoginToken();
            dbUserLoginLog.setIsDelete(1);// 将上一次登录数据 逻辑删除
            sysUserLoginLogMapper.updateById(dbUserLoginLog);

        }
        // token失效了或者是第一次登录
        // 插入当前最新登录日志
        sysUserLoginLog.setIsDelete(0);
        int result = sysUserLoginLogMapper.insert(sysUserLoginLog);
        log.info("<写入登录日志result:{}>", result);
        if (result > 0 && !StringUtils.isEmpty(loginToken)) {
            // 从redis中移除----
            log.info("<正在删除:{}>", loginToken);
            RedisUtil.delKey(loginToken);
        }
        return true;
    }
}
